package cn.feichanghao.nutz.quickstart.auth;

import javax.servlet.http.HttpSession;

import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.google.common.base.Strings;

import cn.feichanghao.nutz.quickstart.auth.model.User;
import cn.feichanghao.nutz.quickstart.service.UserService;

@IocBean
@InjectName
@At("/auth")
public class AuthModule {
	private static final Log log = Logs.getLog(AuthModule.class);
	@Inject
	private UserService userService;

	/**
	 * 用户登陆验证 : http://localhost:8080/NutzQuickStart/auth/login
	 * <p>
	 * 根据参数 "username" 和 "password" 来验证帐户。
	 * @return JSONType的验证结果
	 */
	@At
	public boolean login(	@Param("username") String userName,
							@Param("password") String password,
							HttpSession session) {
		if (Strings.isNullOrEmpty(userName) && Strings.isNullOrEmpty(password)) {
			return false;
		}
		if (log.isDebugEnabled()) {
			log.debugf("Username:%s,Password:%s!", userName, password);
		}
		User user = userService.login(userName, password);
		if (user != null) {
			session.setAttribute(User.class.getName(), user);
			if (log.isDebugEnabled())
				log.debugf("%s login success!key %s",userName,User.class.getName());
			return true;
		}
		return false;
	}
	
	/**
	 * 用户登陆 : http://localhost:8080/NutzQuickStart/auth/login
	 * 
	 */
	@At
	@Ok("jsp:user/login")
	public void loginf()
	{
		//不需要操作
	}
	
	/**
	 * 
	 * @param session
	 */
	@At
	public void logout(HttpSession session) {
		session.invalidate();
	}
}
